/**
 * YunjNotice
 */
layui.use(['jquery','cookie','yunj'], function () {
    let win = window;
    let doc = document;
    let $ = layui.jquery;

    class YunjNotice {

        constructor() {
            this.boxEl=null;            // 容器元素
            this.numberEl=null;         // 未读数量元素
            this.contentEl=null;        // 内容元素

            this.init();
        }

        // 初始化
        init() {
            let that=this;
            that.initAttr();
            that.setContent();
            that.setEventBind();
        }

        // 设置数据
        initAttr() {
            let that = this;
            that.boxEl=$(".header .top-menu-item.top-notice");
            that.numberEl=that.boxEl.find(">a>.number");
            that.contentEl=that.boxEl.find(".content");
        }

        // 设置内容
        setContent() {
            let that = this;
            yunj.request({
                url: yunj.buildAdminUrl("/notice/top-data"),
                type: "post",
            }).then(function (res) {
                if (res.errcode != 0) {
                    yunj.error(res.msg);
                    return;
                }
                if (res.data.type_list && yunj.isArray(res.data.type_list)) {
                    let headerHtml = "";
                    let bodyHtml = "";
                    let number = 0;
                    let listTypes = [];
                    res.data.type_list.forEach((v,i)=>{
                        headerHtml += `<li class="${i==0?'layui-this':''}" id="top_notice_type_${v.type}_title">${v.type_desc}<span class="count" data-count="${v.count}">(${v.count})</span></li>`;
                        let listHtml = that.generateListItemsHtml(v.items);
                        if (listHtml!=="") {
                            listHtml = `<div class="list-box" id="top_notice_type_${v.type}_list_box" data-args='${JSON.stringify({type:v.type,page:1,pageCount:Math.ceil(v.count/v.page_size)})}'>
                                            <div class="list-items">
                                                ${listHtml}
                                            </div>
                                            <div class="list-loading" style="display:none;">
                                                <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                                            </div>
                                        </div>
                                        <div class="action-box">
                                            <div class="action read-all" data-type="${v.type}">全部已读</div>
                                            <div class="sep"></div>
                                            <div class="action view-more" data-view-url="${v.view_more_url}" data-view-title="${v.view_more_title}">查看更多</div>
                                        </div>`;
                            listTypes.push(v.type);
                        }
                        bodyHtml += `<div class="layui-tabs-item${i==0?' layui-show':''}" id="top_notice_type_${v.type}_content">${listHtml}</div>`;
                        number += v.count;
                    });
                    that.contentEl.html(`<div class="layui-tabs layui-panel">
                                            <ul class="layui-tabs-header">
                                                ${headerHtml}
                                            </ul>
                                            <div class="layui-tabs-body">
                                                ${bodyHtml}
                                            </div>
                                        </div>`);
                    that.numberEl.data("number",number).html(number>99?"99+":number);
                    if (number > 0) {
                        that.numberEl.show();
                    } else {
                        that.numberEl.hide();
                    }
                    // 监听滚动事件
                    listTypes.forEach(type=>{
                        // 此处不能使用 that.contentEl.on('scroll', '.list-items'...) 只适用于支持冒泡的事件（如 click、change），而 scroll 事件不冒泡。
                        $(`#top_notice_type_${type}_list_box`).on('scroll', function() {
                            const listBoxEl = $(this);
                            // 计算距离底部的距离
                            const scrollTop = listBoxEl.scrollTop();
                            const visibleHeight = listBoxEl.innerHeight();
                            const contentHeight = listBoxEl[0].scrollHeight;
                            const distanceToBottom = contentHeight - scrollTop - visibleHeight;
                            // 当滚动到距离底部100px时触发
                            if (distanceToBottom <= 100) {
                                that.loadList(listBoxEl);   // 加载列表数据
                            }
                        });
                    });
                }
            });
        }

        // 加载列表数据
        loadList(listBoxEl){
            let that = this;
            let args = listBoxEl.data("args");
            let loadingEl = listBoxEl.find(".list-loading");
            if (++args.page > args.pageCount || yunj.isVisible(loadingEl)) {
                // 正在加载中，则不执行
                return;
            }
            loadingEl.show();
            yunj.request({
                url: yunj.buildAdminUrl("/notice/unread-list"),
                data: {
                    type: args.type,
                    page: args.page,
                },
                type:"post",
            }).then(res=>{
                if (res.errcode != 0) {
                    yunj.error(res.msg);
                    return;
                }
                if (res.data.items && yunj.isArray(res.data.items)) {
                    let listItemsHtml = that.generateListItemsHtml(res.data.items);
                    listBoxEl.find(".list-items").append(listItemsHtml);
                }
                listBoxEl.attr("data-args",JSON.stringify(args));
                loadingEl.hide();
            });
        }

        generateListItemsHtml(items) {
            let html = "";
            items.forEach(v=>{
                html += `<div class="item" id="top_notice_type_${v.type}_${v.id}" title="${v.desc}" data-args='${JSON.stringify(v)}'>
                            <i class="${v.icon}"></i>
                            <div class="message">
                                <div class="desc">${v.desc}</div>
                                <div class="time">${v.created_at}</div>
                            </div>
                        </div>`;
            });
            return html;
        }

        // 处理已读
        handleRead(type,ids = []) {
            let that = this;
            yunj.request({
                url: yunj.buildAdminUrl("/notice/read"),
                data: {
                    type: type,
                    ids: ids,
                },
                type:"post",
            }).then(res=>{
                if (res.errcode != 0) {
                    yunj.error(res.msg);
                    return;
                }
                let number = that.numberEl.data("number");  // 总数量
                let countEl = $(`#top_notice_type_${type}_title .count`);
                let count = countEl.data("count");  // 类型数量
                let removeCount = 0;    // 删除数量
                if (ids.length > 0) {
                    ids.forEach(id=>{
                        let itemEl = $(`#top_notice_type_${type}_${id}`);
                        if (itemEl.length > 0) {
                            itemEl.remove();
                            removeCount++;
                        }
                    });
                } else {
                    $(`#top_notice_type_${type}_content`).html('');
                    removeCount = count;
                }
                // 类型未读数量
                count -= removeCount;
                if (count < 0) {
                    count = 0;
                }
                countEl.data("count",count).html(`(${count})`);
                // 总未读数量
                number -= removeCount;
                if (number < 0) {
                    number = 0;
                }
                that.numberEl.data("number",number).html(number > 99 ? "99+" : number);
                if (number > 0) {
                    that.numberEl.show();
                } else {
                    that.numberEl.hide();
                }
            });
        }

        // 设置类型内容
        setEventBind(){
            let that = this;

            that.contentEl.on("click",".list-items .item",function(){
                let itemEl = $(this);
                let args = itemEl.data("args");
                if (!args.view_url) {
                    return;
                }
                that.handleRead(args.type,[args.id]);   // 处理已读
                yunj.hideTopMenuItemShade();            // 隐藏顶部菜单遮罩
                yunj.openTab(args.view_url,args.view_title);
            });

            // 全部已读
            that.contentEl.on("click",".action-box .read-all",function(){
                let type = $(this).data("type");
                that.handleRead(type);
            });

            // 查看更多
            that.contentEl.on("click",".action-box .view-more",function(){
                let el = $(this);
                let viewUrl = el.data("viewUrl");
                if (!viewUrl) {
                    return;
                }
                let viewTitle = el.data("viewTitle");
                yunj.hideTopMenuItemShade();    // 隐藏顶部菜单遮罩
                yunj.openTab(viewUrl,viewTitle);
            });
        }
    }

    win.yunj.notice=new YunjNotice();
});